package com.earth.c.plugins.shiro;

import java.io.Serializable;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ShiroSessionManager extends DefaultWebSessionManager {

	private static final String TOKEN = "token";

	private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

	@Override
	protected Serializable getSessionId(ServletRequest servletRequest, ServletResponse response) {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String sessionId =request.getHeader(TOKEN);//请求头中有 token 则其值为sessionId
		if (null != sessionId && !"".equals(sessionId) && !"null".contentEquals(sessionId)) {
			log.debug("token=" + sessionId);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
			return sessionId;
		} else {
			// 否则按默认规则从cookie取sessionId
			return super.getSessionId(request, response);
		}
	}

	@Override
	protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
		Serializable sessionId = getSessionId(sessionKey);
		ServletRequest request = null;
		if (sessionId instanceof WebSessionKey) {
			request = ((WebSessionKey) sessionKey).getServletRequest();
		}
		if (request != null && sessionId != null) {
			return (Session) request.getAttribute(sessionId.toString());
		}

		Session session = super.retrieveSession(sessionKey);
		if (request != null && sessionId != null) {
			request.setAttribute(sessionId.toString(), session);
		}
		return session;
	}
}
